﻿package component.fileupload.service;

import java.io.InputStream;
import java.util.Map;

import component.fileupload.exception.FileUploadException;
import component.fileupload.util.FileUtil;
import component.fileupload.vo.UploadFileVO;

/**
 * 文件上传的服务类
 */
public class FileUploadService implements IFileUploadService {
	public String saveFile(String realPath, String relativePath,
			String fileName, InputStream in) throws FileUploadException {
		String saveFileName = FileUtil.getSaveFileName(fileName, null);
		String serverSaveFilePath = FileUtil.changeSlash(realPath)
				+ relativePath + FileUtil.getFileSeparator() + saveFileName;
		String dbSaveFilePath = relativePath + FileUtil.getFileSeparator()
				+ saveFileName;

		FileUtil.saveFile(serverSaveFilePath, in);

		return dbSaveFilePath;
	}

	public void saveFile(String realPath, String relativePath, UploadFileVO vo)
			throws FileUploadException {
		// 获得上传文件的文件名
		String fileName = FileUtil.getFileNameFromFilePath(vo.getFilePath());
		vo.setFileName(fileName);

		String saveFileName = FileUtil.getSaveFileName(fileName, null);
		vo.setSaveFileName(saveFileName);

		String serverSaveFilePath = FileUtil.changeSlash(realPath)
				+ relativePath + FileUtil.getFileSeparator() + saveFileName;
		vo.setServerSaveFilePath(serverSaveFilePath);
		System.out.println("服务器的保存路径 = " + serverSaveFilePath);

		String dbSaveFilePath = relativePath + FileUtil.getFileSeparator()
				+ saveFileName;
		vo.setDbSaveFilePath(dbSaveFilePath);
		System.out.println("数据库的保存路径 = " + dbSaveFilePath);

		if (vo.getInputStream() != null) {
			FileUtil.saveFile(serverSaveFilePath, vo.getInputStream());
		} else if (vo.getBinArray() != null && vo.getStartData() != 0) {
			FileUtil.saveFile(serverSaveFilePath, vo.getBinArray(), vo
					.getStartData(), vo.getFileSize());
		}
	}

	public void saveFiles(String realPath, String relativePath, Map fileInfoMap)
			throws FileUploadException {
		try {
			for (int i = 0; i < fileInfoMap.size(); i++) {
				UploadFileVO vo = (UploadFileVO) fileInfoMap
						.get(new Integer(i));

				this.saveFile(realPath, relativePath, vo);
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new FileUploadException(e);
		}
	}
}
